# coding=utf-8
from manager.state import State
import codecs
import json

import os


class FileState(State):
    def __init__(self, file_name, template):
        super(FileState, self).__init__()
        self.file_name = file_name
        self.template = template

    def init_state(self):
        if not os.path.exists(os.path.dirname(self.file_name)):
            os.makedirs(os.path.dirname(self.file_name))

        if os.path.exists(self.file_name):
            os.remove(self.file_name)

        with codecs.open(self.file_name, mode='w+', encoding='utf-8') as opened_file:
            line = json.dumps(self.template)
            opened_file.write(line.decode("unicode_escape"))

    def load_state(self):
        if not os.path.exists(self.file_name):
            self.init_state()
        with codecs.open(self.file_name, mode='r', encoding='utf-8') as opened_file:
            self.content = json.load(opened_file)

    def save_state(self):
        with codecs.open(self.file_name, mode='w+', encoding='utf-8') as opened_file:
            line = json.dumps(self.content)
            opened_file.write(line.decode("unicode_escape"))
